<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElSelect, ElOption, ElButton } from 'element-plus'
import myAxios from '../../../plugins/myAxios'
import { ElMessage } from 'element-plus'

// 分页数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索条件
const searchForm = ref({
  subjectId: '',
  chapterId: ''
})

// 科目和章节选项
const subjectOptions = ref([])
const chapterOptions = ref([])


// 题目类型映射
const questionTypeMap = {
  1: '选择题',
  2: '综合题'
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  return questionTypeMap[type] || '未知类型'
}


// 获取科目列表
const getSubjects = async () => {
  try {
    const data = await myAxios.get('/teacher/researchInfo/subject/list')
    subjectOptions.value = data.map(item => ({
      value: item.id,
      label: item.subjectName,
    }))
  } catch (error) {
    ElMessage.error('获取科目列表失败：' + error)
  }
}

// 处理科目选择变化
const handleSubjectChange = async (subjectId) => {
  searchForm.value.chapterId = '' // 重置章节选择
  chapterOptions.value = [] // 清空章节选项
  if (subjectId) {
    await getChapters(subjectId)
  }
}

// 获取章节列表
const getChapters = async (subjectId) => {
  try {
    const data = await myAxios.get(`/teacher/researchInfo/chapter/getBySubject/${subjectId}`)
    chapterOptions.value = data.map(item => ({
      value: item.id,
      label: item.chapterName,
    }))
  } catch (error) {
    ElMessage.error('获取章节列表失败：' + error)
  }
}

// 获取答题数据
const getAnswerData = async () => {
  try {
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      subjectId: searchForm.value.subjectId,
      chapterId: searchForm.value.chapterId
    }
    const data = await myAxios.get('/teacher/answer/data/test/page', { params })
    tableData.value = data.records
    total.value = Number(data.total) || 0  // 确保 total 有值
  } catch (error) {
    ElMessage.error('获取答题数据失败：' + error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getAnswerData()
}

// 添加重置搜索方法
const resetSearch = () => {
  searchForm.value = {
    subjectId: '',
    chapterId: ''
  }
  currentPage.value = 1
  getAnswerData()
}

onMounted(() => {
  getSubjects()
  getAnswerData()
})
</script>

<template>
  <div class="answer-data">
    <!-- 标题 -->
    <div class="page-header">
      <h2>答题数据分析</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-items">
        <el-select 
          v-model="searchForm.subjectId" 
          placeholder="请选择科目" 
          @change="handleSubjectChange"
          clearable
        >
          <el-option
            v-for="item in subjectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select 
          v-model="searchForm.chapterId" 
          placeholder="请选择章节"
          clearable
        >
          <el-option
            v-for="item in chapterOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="questionContent" label="题目内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="questionType" label="题目类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.questionType === 1 ? 'success' : 'warning'">
              {{ scope.row.questionType === 1 ? '选择题' : '综合题' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="subjectName" label="科目" width="160" align="center" />
        <el-table-column prop="chapterName" label="章节" width="160" align="center" />
        <el-table-column prop="totalAnswerCount" label="答题总数" width="100" align="center" />
        <el-table-column prop="totalCorrectRate" label="正确率" width="130" align="center">
          <template #default="scope">
            <span :class="{'high-rate': scope.row.totalCorrectRate >= 80}">
              {{ (scope.row.totalCorrectRate ?? 0) + '%' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="选项分布" width="150" align="center">
          <template #default="scope">
            <template v-if="scope.row.questionType === 1">
              <div class="option-distribution">
                <div class="option-item" v-for="(option, index) in ['A', 'B', 'C', 'D']" :key="option">
                  <span class="option-label">{{ option }}:</span>
                  <span class="option-count">{{ scope.row[`option${option}Count`] || 0 }}</span>
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="getAnswerData"
        @size-change="getAnswerData"
      />
    </div>
  </div>
</template>

<style scoped lang="less">
.answer-data {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);

  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
      font-weight: 600;
    }
  }

  .search-bar {
    padding: 24px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;

    .search-items {
      display: flex;
      gap: 16px;
      align-items: center;
      
      :deep(.el-select) {
        width: 180px;
      }
    }
  }

  .table-container {
    background-color: #fff;
    padding: 24px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;

    :deep(.el-table) {
      .high-rate {
        color: #67c23a;
        font-weight: bold;
      }
    }

    .option-distribution {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .option-item {
        display: flex;
        justify-content: space-between;
        padding: 0 12px;

        .option-label {
          color: #606266;
        }

        .option-count {
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }

  .pagination-container {
    background-color: #fff;
    padding: 16px 24px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: flex-end;
  }
}
</style>
